import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import store from '@/store'  //默认找index
import { getToken } from '@/utils/auth'
import {Promise} from 'q'   //ES6新语法，引入请求
import router from '@/router'

const service = axios.create({
  // baseURL:'/api',  //baseURL + requesty url  http://www.xxx.com./c/c/c/c/c  组成网址
  baseURL:process.env.VUE_APP_BASE_API, //env开发
  timeout:10000
})


//请求拦截器
service.interceptors.request.use( (config)=>{
  //注入token
  if(store.getters.token){
    config.headers.Authorization = `Bearer ${store.getters.token}`
  }

  return config
}, (error)=>{
  //失败时执行
  return Promise.reject(error)
} )

//响应拦截器
service.interceptors.response.use( (response)=>{

  // response --> data ，axios 默认包裹了data

  if(response.data instanceof Blob) return response.data

  const { data,message,success } = response.data
  if(success){
    return data
  }else{
    Message({ type:'error' , message })

    return Promise.reject(new Error(message))
  }
}, async (error)=>{
  if(error.response.status === 401){
    //token超时
    Message({type:'warning',message:'你的token超时了!!!'})
    //退出
    await store.dispatch('user/logout')
    router.push('/login')
    return Promise.reject(error)
  }
})


export default service